﻿using LinqToTwitter;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using TweetsTranslate.Models;

namespace TweetsTranslate.Providers
{
    public class TwitterProvider
    {
        private TwitterContext twitterCtx;
        public TwitterProvider()
        {
            var auth = new ApplicationOnlyAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]
                }
            };


            auth.Authorize();
            twitterCtx = new TwitterContext(auth);
        }

        public List<TweetModel> SearchTweets(string userId, string keys, string language, int noResults, ref string errorMessage)
        {
            List<TweetModel> listTweets = new List<TweetModel>();

            if (userId != null && userId.Length > 0)
            {
                try
                {
                    var statusTweets =
                        from tweet in twitterCtx.Status
                        where tweet.Type == StatusType.User
                              && tweet.ScreenName == userId
                              && tweet.Count == noResults
                        select tweet;
                    foreach (var status in statusTweets)
                    {
                        listTweets.Add(new TweetModel(status.Text, status.User.Identifier.ScreenName, status.CreatedAt, status.StatusID));
                    }
                }
                catch (Exception ex)
                {
                    errorMessage = "The provided user id doesn't exists.";
                    return listTweets;
                }
            }
            else
            {
                var statusTweets =
                    (from tweet in twitterCtx.Search
                     where tweet.Type == SearchType.Search
                           && tweet.Query == keys
                         
                           && tweet.SearchLanguage == language
                           && tweet.Count == noResults
                     select tweet).SingleOrDefault();

                foreach (var status in statusTweets.Statuses)
                {
                    listTweets.Add(new TweetModel(status.Text, status.User.Identifier.ScreenName, status.CreatedAt, status.StatusID));
                }
            }
            return listTweets;
        }
    }
}